package Reflection;

import java.lang.reflect.Field;

public class demo9 {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        //先获取class对象
        Class c = Cat.class;

        //Cat 的实例对象
        Cat cat = new Cat();
        //再获取变量对象
        Field fieldName = c.getDeclaredField("name");
        Field fieldAge = c.getDeclaredField("age");

        //禁止检查访问控制
        fieldName.setAccessible(true);
        fieldAge.setAccessible(true);
        //进行赋值操作
        fieldName.set(cat,"小板");
        fieldAge.set(cat,2);

        //再进行取值操作
        String name = (String) fieldName.get(cat);
        int age = (int) fieldAge.get(cat);

        //查看是否赋值成功
        System.out.println(cat);

    }
}
